package com.quanquan.user.service.app;

import base.AuthConst;
import com.alibaba.fastjson.JSONObject;
import com.quanquan.user.entity.User;
import com.quanquan.user.repository.UserRepository;
import com.quanquan.user.request.RegisterRequestBody;
import com.quanquan.user.request.UserRequestBody;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import utils.AESUtil;
import utils.Request;
import utils.SMSUtils;
import utils.StringUtil;

import java.util.concurrent.TimeUnit;

/**
 * 注册校验
 * @author qianzhihao
 */
@Service
public class AppUserService {

    private final static String SENDSMS = "smsMobile-";
    private static final String PREFIX = "userMobile-";
    private static final Integer EXPIRESMS = 300;
    private static final String SOURCE = "yuyanApp";
    private final StringRedisTemplate redisTemplate;
    private final UserRepository userRepository;

    @Autowired
    public AppUserService(StringRedisTemplate redisTemplate, UserRepository userRepository) {
        this.redisTemplate = redisTemplate;
        this.userRepository = userRepository;
    }

    /**
     * 根据Id查询用户
     *
     * @param id
     * @return
     */
    public User getById(String id) {
        return userRepository.getOne(id);
    }


    /**
     * 用户注册
     *
     * @param requestBody
     * @return
     */
    public User create(UserRequestBody requestBody) {
        String phone = requestBody.getPhone();
        User user = new User();
        user.setPhone(phone);
        user.setSource(SOURCE);
        User save = userRepository.save(user);
        // asynRegister(phone);
        return save;
    }


    /**
     * 校验验证码
     *
     * @param mobile
     * @param code
     * @return
     */
    public Boolean verifyCode(String mobile, String code) {
        if (StringUtils.isNotEmpty(mobile) && StringUtils.isNotEmpty(code)) {
            return code.equals(getCode(mobile));
        } else {
            return false;
        }
    }

    /**
     * 根据号码从缓存中获取验证码
     *
     * @param mobile
     * @return
     */
    public String getCode(String mobile) {
        return redisTemplate.opsForValue().get(PREFIX + mobile);
    }

    public String getSMSCode(String mobile) {
        return redisTemplate.opsForValue().get(SENDSMS + mobile);
    }

    public boolean removeSMSCode(String mobile){
        String phoneMsg = redisTemplate.opsForValue().get(SENDSMS + mobile);
        if(StringUtil.isNotEmpty(phoneMsg)){
            Boolean result = redisTemplate.delete(SENDSMS + mobile);
            return result;
        }
       return false;


    }




    /**
     * 发送验证码(宝乐汇)
     *
     * @param mobile
     * @return 是否发送成功
     */
    public Boolean sendMsg(String mobile) {
        String randomCode = getNewRandomCode(6);
        String message = " 您的验证码是" + randomCode + "，5分钟内有效。如非您本人操作，请忽略...【宝乐汇】";
        boolean sendResult = SMSUtils.sendMessage(mobile, message);
        //向redis中存验证码，保存时间1分钟
        redisTemplate.opsForValue().set(SENDSMS + mobile, randomCode, EXPIRESMS, TimeUnit.SECONDS);

        return sendResult;
    }

    /**
     * 根据需要生成指定长度的纯数字随机数,这个随机数的每一位都是从(0-9)这个产生的一位
     *
     * @param codeLen
     * @return
     */
    private String getNewRandomCode(int codeLen) {
        java.util.Random randomCode = new java.util.Random();
        StringBuilder strCode = new StringBuilder();
        while (codeLen > 0) {
            int charCode = randomCode.nextInt(9);
            strCode.append(charCode);
            codeLen--;
        }
        return strCode.toString();
    }


    //获取微信用户的手机号
    public String getMobileBySessionKey(RegisterRequestBody requestBody) {
        JSONObject json = getWeChatObj(requestBody);
        if (!json.containsKey("session_key")) {
            return null;
        }
        String sessionKey = json.get("session_key").toString();
        String result;
        try {
            result = AESUtil.wxDecrypt(requestBody.getEncryptedData(), sessionKey, requestBody.getIv());
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return result;
    }

    private JSONObject getWeChatObj(RegisterRequestBody requestBody) {
        String params = "appid=" + AuthConst.WECHAT.ID + "&secret=" + AuthConst.WECHAT.SECRET + "&js_code=" + requestBody.getCode() + "&grant_type="
                + AuthConst.WECHAT.GRANT;
        String sr = Request.sendGet1("https://api.weixin.qq.com/sns/jscode2session", params);
        return JSONObject.parseObject(sr);
    }

}
